import React, { useState, useEffect } from 'react';
import {
  Container,
  Grid,
  Typography,
  Box,
  Button,
  Card,
  CardContent,
  CardActions,
  CardMedia,
  useTheme,
  alpha,
  Avatar,
  List,
  ListItem,
  ListItemText,
  ListItemAvatar,
  Divider,
  Paper
} from '@mui/material';
import {
  CalculateOutlined,
  EmojiEventsOutlined,
  GroupOutlined,
  TrendingUpOutlined,
  WhatshotOutlined,
  EmojiEvents,
  LocalActivity,
  Nature
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

function Home() {
  const theme = useTheme();
  const navigate = useNavigate();
  const [latestChallenges, setLatestChallenges] = useState([]);
  const [topUsers, setTopUsers] = useState([]);
  const [upcomingEvents, setUpcomingEvents] = useState([]);

  // 获取最新挑战
  useEffect(() => {
    const fetchLatestChallenges = async () => {
      try {
        const response = await axios.get('/api/challenges?limit=3');
        setLatestChallenges(response.data);
      } catch (error) {
        console.error('获取最新挑战失败:', error);
      }
    };
    fetchLatestChallenges();
  }, []);

  const features = [
    {
      title: '碳足迹计算',
      description: '精确计算您的日常活动产生的碳排放量',
      icon: <CalculateOutlined sx={{ fontSize: 40 }} />,
      path: '/calculator',
      image: 'http://localhost:5001/images/calculator.jpg'
    },
    {
      title: '环保挑战',
      description: '参与各种环保挑战，赢取积分和奖励',
      icon: <EmojiEventsOutlined sx={{ fontSize: 40 }} />,
      path: '/challenges',
      image: 'http://localhost:5001/images/challenges.jpg'
    },
    {
      title: '社区资源',
      description: '发现附近的环保设施和活动',
      icon: <GroupOutlined sx={{ fontSize: 40 }} />,
      path: '/community',
      image: '/images/community.jpg'
    },
    {
      title: '进度追踪',
      description: '查看您的环保成就和贡献',
      icon: <TrendingUpOutlined sx={{ fontSize: 40 }} />,
      path: '/dashboard',
      image: '/images/progress.jpg'
    }
  ];

  // 示例数据 - 实际应用中应从API获取
  const achievements = [
    { title: '减少碳排放', value: '2.5吨', icon: <Nature color="primary" /> },
    { title: '完成挑战', value: '12个', icon: <EmojiEvents color="primary" /> },
    { title: '获得积分', value: '1580分', icon: <WhatshotOutlined color="primary" /> },
    { title: '参与活动', value: '8次', icon: <LocalActivity color="primary" /> }
  ];

  const handleStart = () => {
    // 跳转到碳计算器页面
    navigate('/calculator');
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        background: `linear-gradient(to bottom, ${alpha(theme.palette.primary.main, 0.1)}, ${alpha(theme.palette.primary.main, 0.05)})`
      }}
    >
      {/* 主横幅 */}
      <Box
        sx={{
          py: 8,
          textAlign: 'center',
          background: `linear-gradient(to bottom, ${theme.palette.primary.main}, ${theme.palette.primary.dark})`,
          color: 'white'
        }}
      >
        <Container maxWidth="md">
          <Typography variant="h3" component="h1" gutterBottom fontWeight="bold">
            让环保成为生活方式
          </Typography>
          <Typography variant="h6" paragraph sx={{ mb: 4, opacity: 0.9 }}>
            EcoTrack 帮助您轻松践行环保理念，记录每一个对地球有益的行动
          </Typography>
          <Typography variant="body1" paragraph sx={{ mb: 4, opacity: 0.8 }}>
            加入我们的环保社区，通过有趣的挑战和互动，一起为可持续发展贡献力量
          </Typography>
          <Button
            variant="contained"
            size="large"
            onClick={handleStart}
            sx={{
              bgcolor: 'white',
              color: 'primary.main',
              '&:hover': {
                bgcolor: alpha('#fff', 0.9)
              }
            }}
          >
            开始环保之旅
          </Button>
        </Container>
      </Box>

      {/* 添加项目介绍部分 */}
      <Box sx={{ py: 8, bgcolor: 'background.paper' }}>
        <Container maxWidth="lg">
          <Grid container spacing={4} alignItems="center">
            <Grid item xs={12} md={6}>
              <Typography variant="h4" gutterBottom color="primary.main">
                为什么选择 EcoTrack？
              </Typography>
              <Typography variant="body1" paragraph>
                EcoTrack 是一个专注于环保的社交平台，我们相信每个人的小小行动都能带来巨大改变。
              </Typography>
              <Box sx={{ mt: 3 }}>
                <Typography variant="h6" gutterBottom color="primary.main">
                  我们的优势：
                </Typography>
                <ul style={{ paddingLeft: '20px' }}>
                  <li>
                    <Typography variant="body1" paragraph>
                      <strong>简单易用</strong> - 通过直观的界面记录您的环保行动
                    </Typography>
                  </li>
                  <li>
                    <Typography variant="body1" paragraph>
                      <strong>社区互动</strong> - 与志同道合的环保爱好者交流经验
                    </Typography>
                  </li>
                  <li>
                    <Typography variant="body1" paragraph>
                      <strong>趣味挑战</strong> - 参与环保挑战，赢取积分和徽章
                    </Typography>
                  </li>
                  <li>
                    <Typography variant="body1" paragraph>
                      <strong>科学量化</strong> - 精确计算您的碳足迹和环保贡献
                    </Typography>
                  </li>
                </ul>
              </Box>
            </Grid>
            <Grid item xs={12} md={6}>
              <Box sx={{ position: 'relative', height: '400px' }}>
                <img
                  src="/images/eco-lifestyle.jpg"
                  alt="环保生活方式"
                  style={{
                    width: '100%',
                    height: '100%',
                    objectFit: 'cover',
                    borderRadius: '12px'
                  }}
                />
              </Box>
            </Grid>
          </Grid>
        </Container>
      </Box>

      {/* 添加使用步骤说明 */}
      <Box sx={{ py: 8, bgcolor: alpha(theme.palette.primary.main, 0.05) }}>
        <Container maxWidth="lg">
          <Typography variant="h4" align="center" gutterBottom color="primary.main">
            开始您的环保之旅
          </Typography>
          <Typography variant="body1" align="center" paragraph sx={{ mb: 6 }}>
            只需简单几步，即可加入我们的环保社区
          </Typography>
          
          <Grid container spacing={4}>
            <Grid item xs={12} md={3}>
              <Box sx={{ textAlign: 'center' }}>
                <Typography variant="h2" color="primary.main" gutterBottom>
                  1
                </Typography>
                <Typography variant="h6" gutterBottom>
                  注册账号
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  创建您的个人环保档案
                </Typography>
              </Box>
            </Grid>
            <Grid item xs={12} md={3}>
              <Box sx={{ textAlign: 'center' }}>
                <Typography variant="h2" color="primary.main" gutterBottom>
                  2
                </Typography>
                <Typography variant="h6" gutterBottom>
                  计算碳足迹
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  了解您的环境影响
                </Typography>
              </Box>
            </Grid>
            <Grid item xs={12} md={3}>
              <Box sx={{ textAlign: 'center' }}>
                <Typography variant="h2" color="primary.main" gutterBottom>
                  3
                </Typography>
                <Typography variant="h6" gutterBottom>
                  参与挑战
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  完成环保任务获得积分
                </Typography>
              </Box>
            </Grid>
            <Grid item xs={12} md={3}>
              <Box sx={{ textAlign: 'center' }}>
                <Typography variant="h2" color="primary.main" gutterBottom>
                  4
                </Typography>
                <Typography variant="h6" gutterBottom>
                  分享成果
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  激励更多人加入环保行动
                </Typography>
              </Box>
            </Grid>
          </Grid>
        </Container>
      </Box>

      {/* 成就统计 */}
      <Container maxWidth="lg" sx={{ mt: -4 }}>
        <Grid container spacing={2}>
          {achievements.map((achievement) => (
            <Grid item xs={12} sm={6} md={3} key={achievement.title}>
              <Paper
                elevation={2}
                sx={{
                  p: 3,
                  textAlign: 'center',
                  height: '100%',
                  bgcolor: 'background.paper',
                  borderRadius: 2
                }}
              >
                <Box sx={{ mb: 1 }}>{achievement.icon}</Box>
                <Typography variant="h4" gutterBottom sx={{ fontWeight: 'bold' }}>
                  {achievement.value}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  {achievement.title}
                </Typography>
              </Paper>
            </Grid>
          ))}
        </Grid>
      </Container>

      {/* 功能卡片 */}
      <Container maxWidth="lg" sx={{ py: 8 }}>
        <Grid container spacing={4}>
          {features.map((feature) => (
            <Grid item xs={12} sm={6} md={3} key={feature.title}>
              <Card
                sx={{
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  transition: 'transform 0.2s',
                  '&:hover': {
                    transform: 'translateY(-8px)'
                  }
                }}
              >
                <CardMedia
                  component="img"
                  height="140"
                  image={feature.image}
                  alt={feature.title}
                />
                <CardContent sx={{ flexGrow: 1, textAlign: 'center' }}>
                  <Box sx={{ mb: 2, color: 'primary.main' }}>
                    {feature.icon}
                  </Box>
                  <Typography variant="h6" gutterBottom>
                    {feature.title}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    {feature.description}
                  </Typography>
                </CardContent>
                <CardActions sx={{ justifyContent: 'center', pb: 2 }}>
                  <Button
                    variant="outlined"
                    onClick={() => navigate(feature.path)}
                    sx={{ borderRadius: 20 }}
                  >
                    了解更多
                  </Button>
                </CardActions>
              </Card>
            </Grid>
          ))}
        </Grid>
      </Container>

      {/* 最新挑战和活动 */}
      <Box sx={{ bgcolor: 'background.paper', py: 8 }}>
        <Container maxWidth="lg">
          <Grid container spacing={4}>
            {/* 最新挑战 */}
            <Grid item xs={12} md={6}>
              <Typography variant="h5" gutterBottom color="primary">
                最新挑战
              </Typography>
              <List>
                {latestChallenges.map((challenge, index) => (
                  <React.Fragment key={challenge._id}>
                    <ListItem
                      button
                      onClick={() => navigate(`/challenges/${challenge._id}`)}
                    >
                      <ListItemAvatar>
                        <Avatar sx={{ bgcolor: 'primary.main' }}>
                          <EmojiEventsOutlined />
                        </Avatar>
                      </ListItemAvatar>
                      <ListItemText
                        primary={challenge.title}
                        secondary={`${challenge.points}积分 · ${challenge.participants?.length || 0}人参与`}
                      />
                    </ListItem>
                    {index < latestChallenges.length - 1 && <Divider />}
                  </React.Fragment>
                ))}
              </List>
              <Box sx={{ mt: 2, textAlign: 'center' }}>
                <Button
                  variant="outlined"
                  onClick={() => navigate('/challenges')}
                  sx={{ borderRadius: 20 }}
                >
                  查看更多挑战
                </Button>
              </Box>
            </Grid>

            {/* 近期活动 */}
            <Grid item xs={12} md={6}>
              <Typography variant="h5" gutterBottom color="primary">
                近期活动
              </Typography>
              <List>
                {[
                  {
                    title: '社区环保讲座',
                    time: '2024-03-20 14:00',
                    location: '文化路社区中心'
                  },
                  {
                    title: '垃圾分类活动',
                    time: '2024-03-22 09:00',
                    location: '市民广场'
                  },
                  {
                    title: '植树活动',
                    time: '2024-03-25 10:00',
                    location: '城市公园'
                  }
                ].map((event, index, arr) => (
                  <React.Fragment key={event.title}>
                    <ListItem button onClick={() => navigate('/community')}>
                      <ListItemAvatar>
                        <Avatar sx={{ bgcolor: 'secondary.main' }}>
                          <LocalActivity />
                        </Avatar>
                      </ListItemAvatar>
                      <ListItemText
                        primary={event.title}
                        secondary={`${event.time} · ${event.location}`}
                      />
                    </ListItem>
                    {index < arr.length - 1 && <Divider />}
                  </React.Fragment>
                ))}
              </List>
              <Box sx={{ mt: 2, textAlign: 'center' }}>
                <Button
                  variant="outlined"
                  onClick={() => navigate('/community')}
                  sx={{ borderRadius: 20 }}
                >
                  浏览更多活动
                </Button>
              </Box>
            </Grid>
          </Grid>
        </Container>
      </Box>

      {/* 环保小贴士 */}
      <Box sx={{ bgcolor: 'background.paper', py: 8 }}>
        <Container maxWidth="lg">
          <Typography variant="h4" align="center" gutterBottom>
            环保小贴士
          </Typography>
          <Grid container spacing={4} sx={{ mt: 2 }}>
            <Grid item xs={12} md={4}>
              <Typography variant="h6" gutterBottom color="primary">
                节约用电
              </Typography>
              <Typography variant="body1">
                使用节能电器，随手关灯，充分利用自然光
              </Typography>
            </Grid>
            <Grid item xs={12} md={4}>
              <Typography variant="h6" gutterBottom color="primary">
                减少浪费
              </Typography>
              <Typography variant="body1">
                自带购物袋，选择可重复使用的产品
              </Typography>
            </Grid>
            <Grid item xs={12} md={4}>
              <Typography variant="h6" gutterBottom color="primary">
                绿色出行
              </Typography>
              <Typography variant="body1">
                多步行，骑自行车，使用公共交通工具
              </Typography>
            </Grid>
          </Grid>
        </Container>
      </Box>

      {/* 号召行动 */}
      <Box
        sx={{
          py: 6,
          textAlign: 'center',
          bgcolor: 'background.paper',
          borderTop: 1,
          borderColor: 'divider'
        }}
      >
        <Container maxWidth="sm">
          <Typography variant="h4" gutterBottom>
            立即加入我们
          </Typography>
          <Typography variant="body1" paragraph color="text.secondary">
            每个人的小小行动，都能为地球带来巨大改变
          </Typography>
          <Button
            variant="contained"
            size="large"
            onClick={() => navigate('/calculator')}
            sx={{ borderRadius: 20 }}
          >
            开始行动
          </Button>
        </Container>
      </Box>
    </Box>
  );
}

export default Home; 